package com.rskj.cashbook.controller;

import com.rskj.cashbook.response.ResponseEntity;
import com.rskj.cashbook.util.JwtUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("user/device")
@AllArgsConstructor
public class UserDeviceController {

    private final JwtUtil jwtUtil;

    /**
     * 获取当前用户的活跃设备数量
     */
    @GetMapping("/count")
    public ResponseEntity<Map<String, Object>> getActiveDeviceCount() {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            
            long deviceCount = jwtUtil.getUserActiveTokenCount(username);
            
            Map<String, Object> result = new HashMap<>();
            result.put("username", username);
            result.put("activeDeviceCount", deviceCount);
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("Error getting active device count: {}", e.getMessage(), e);
            return ResponseEntity.failGeneric("获取设备数量失败: " + e.getMessage());
        }
    }

    /**
     * 获取当前用户的所有活跃设备信息
     */
    @GetMapping("/list")
    public ResponseEntity<List<Map<String, Object>>> getActiveDevices() {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            
            List<Map<String, Object>> devices = jwtUtil.getUserActiveDevices(username);
            
            return ResponseEntity.ok(devices);
        } catch (Exception e) {
            log.error("Error getting active devices: {}", e.getMessage(), e);
            return ResponseEntity.failGeneric("获取设备列表失败: " + e.getMessage());
        }
    }

    /**
     * 强制用户下线（删除所有token）
     */
    @PostMapping("/force-logout")
    public ResponseEntity<String> forceLogout() {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            
            boolean success = jwtUtil.forceUserLogout(username);
            
            if (success) {
                return ResponseEntity.ok("强制下线成功");
            } else {
                return ResponseEntity.fail("强制下线失败");
            }
        } catch (Exception e) {
            log.error("Error forcing logout: {}", e.getMessage(), e);
            return ResponseEntity.fail("强制下线失败: " + e.getMessage());
        }
    }

    /**
     * 下线特定设备
     */
    @PostMapping("/logout-device")
    public ResponseEntity<String> logoutDevice(@RequestParam String deviceId) {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            
            boolean success = jwtUtil.logoutDevice(username, deviceId);
            
            if (success) {
                return ResponseEntity.ok("设备下线成功");
            } else {
                return ResponseEntity.fail("设备下线失败");
            }
        } catch (Exception e) {
            log.error("Error logging out device: {}", e.getMessage(), e);
            return ResponseEntity.fail("设备下线失败: " + e.getMessage());
        }
    }
}
